package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    @Override
    public List<User> findAll() {
        String sql="select * from t_users";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(int id) {
        String sql="delete from t_users where id=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addUser(User user) {
        String sql="insert into t_users (name,password,sex,birthday,registTime) value (?,?,?,?,?)";
        Object[] params={user.getName(),user.getPassword(),user.getSex(),user.getBirthday(),user.getRegistTime()};
        try {
            queryRunner.execute(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(User user) {
        String sql="update  t_users set name=?,password=?,sex=?,birthday=?,registTime=? where id=?";
        Object[] params={user.getName(),user.getPassword(),user.getSex(),user.getBirthday(),user.getRegistTime(),user.getId()};
        try {
            queryRunner.execute(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
